import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:gourmet/color/hex.dart';
import 'package:gourmet/extensions/ex_widget.dart';
import 'package:gourmet/utils/colors.dart';
import 'package:gourmet/utils/styles.dart';
import 'package:gourmet/utils/svg.dart';
import 'package:gourmet/utils/tools.dart';

class HelpChatController extends GetxController {
  final double navHeight = 44 + Get.mediaQuery.padding.top;
  final RxList<String> sends = RxList([]);

  late TextEditingController textEditingController;

  @override
  void onInit() {
    textEditingController = ToolsUtils.editingController('');
    super.onInit();
  }

  @override
  void onClose() {
    textEditingController.dispose();
    super.onClose();
  }

  void sendMessage() {
    sends.add(textEditingController.text);
    textEditingController.text = '';
  }
}

class HelpChatPage extends GetView<HelpChatController> {
  const HelpChatPage({super.key});

  @override
  Widget build(BuildContext context) {
    return MediaQuery.removeViewPadding(
      context: context,
      removeBottom: true,
      removeLeft: true,
      removeRight: true,
      removeTop: true,
      child: Scaffold(
        backgroundColor: HexColor(ColorsUtils.colorF7f7),
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(controller.navHeight),
          child: AnnotatedRegion<SystemUiOverlayStyle>(
            value: SystemUiOverlayStyle.dark,
            child: Container(
              color: Colors.white,
              height: controller.navHeight,
              padding: Get.mediaQuery.padding,
              child: Stack(
                children: [
                  Positioned(
                    width: 40,
                    height: 44,
                    top: 0,
                    left: 0,
                    child: Center(
                      child: Icon(
                        CupertinoIcons.chevron_back,
                        size: 20,
                        color: HexColor(ColorsUtils.color0000),
                      ),
                    ).onTap(Get.back),
                  ),
                  Center(
                    child: Text(
                      '在线客服 (9:00-21:00)',
                      softWrap: true,
                      style: StylesUtils.customTextStyle(
                        fontSize: StylesUtils.fontSize16,
                        fontWeight: FontWeight.w700,
                        color: ColorsUtils.color0000,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        body: Obx(
          () => ListView(
            padding: const EdgeInsets.symmetric(horizontal: 15),
            children: [
              // 发送
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: Container(
                      padding: const EdgeInsets.only(right: 10),
                      alignment: Alignment.centerRight,
                      child: LimitedBox(
                        maxWidth: 300,
                        child: Stack(
                          clipBehavior: Clip.none,
                          children: [
                            LayoutBuilder(
                                builder: (BuildContext ctx, BoxConstraints bx) {
                              // 计算高度 和宽度
                              final style = StylesUtils.customTextStyle(
                                color: ColorsUtils.color0000,
                                fontSize: StylesUtils.fontSize15,
                              );
                              String result = '你好，在吗?';
                              double height = ToolsUtils.calculateTextHeight(
                                  value: result, style: style);
                              height = height > 40 ? (height + 20) : 40;
                              double width = ToolsUtils.calculateTextWidth(
                                  value: result, style: style);
                              width = width > 300 ? 300 : width + 15;
                              return Container(
                                margin: const EdgeInsets.only(right: 5),
                                padding: const EdgeInsets.symmetric(
                                    vertical: 10, horizontal: 5),
                                width: width,
                                height: height,
                                alignment: Alignment.centerLeft,
                                decoration: BoxDecoration(
                                  color: HexColor(ColorsUtils.colorA9e9),
                                  borderRadius: BorderRadius.circular(3),
                                ),
                                child: Text(
                                  result,
                                  style: style,
                                ),
                              );
                            }),
                            Positioned(
                              width: 5,
                              height: 40,
                              top: 0,
                              right: 0,
                              child: CustomPaint(
                                size: const Size(5, 40),
                                painter: _SendCustomPainter(8),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  ClipRRect(
                    borderRadius: BorderRadius.circular(2),
                    child: Image.network(
                      'https://img2.baidu.com/it/u=4153415757,176581311&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
                      width: 40,
                      height: 40,
                      fit: BoxFit.fill,
                    ),
                  ),
                ],
              ).marginOnly(top: 10),
              // 接收
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(2),
                    child: Image.network(
                      'https://img2.baidu.com/it/u=1397509398,2387330504&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
                      width: 40,
                      height: 40,
                      fit: BoxFit.fill,
                    ),
                  ),
                  Expanded(
                    child: Container(
                      padding: const EdgeInsets.only(left: 10),
                      alignment: Alignment.centerLeft,
                      child: LimitedBox(
                        maxWidth: 300,
                        child: Stack(
                          clipBehavior: Clip.none,
                          children: [
                            LayoutBuilder(
                                builder: (BuildContext ctx, BoxConstraints bx) {
                              // 计算高度 和宽度
                              final style = StylesUtils.customTextStyle(
                                color: ColorsUtils.color0000,
                                fontSize: StylesUtils.fontSize15,
                              );
                              String result = '亲，请问有什么要咨询？';
                              double height = ToolsUtils.calculateTextHeight(
                                  value: result, style: style);
                              height = height > 40 ? (height + 20) : 40;
                              double width = ToolsUtils.calculateTextWidth(
                                  value: result, style: style);
                              width = width > 300 ? 300 : width + 15;
                              return Container(
                                margin: const EdgeInsets.only(left: 5),
                                padding: const EdgeInsets.symmetric(
                                    vertical: 10, horizontal: 5),
                                width: width,
                                height: height,
                                alignment: Alignment.centerLeft,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(3),
                                ),
                                child: Text(
                                  result,
                                  style: style,
                                ),
                              );
                            }),
                            Positioned(
                              width: 5,
                              height: 40,
                              top: 0,
                              left: 0,
                              child: CustomPaint(
                                size: const Size(5, 40),
                                painter: _ReceiveCustomPainter(8),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ).marginOnly(top: 10),
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: Container(
                      padding: const EdgeInsets.only(right: 10),
                      alignment: Alignment.centerRight,
                      child: LimitedBox(
                        maxWidth: 300,
                        child: Stack(
                          clipBehavior: Clip.none,
                          children: [
                            LayoutBuilder(
                                builder: (BuildContext ctx, BoxConstraints bx) {
                              // 计算高度 和宽度
                              final style = StylesUtils.customTextStyle(
                                color: ColorsUtils.color0000,
                                fontSize: StylesUtils.fontSize15,
                              );
                              String result = '你好，商家一直不接单怎么办';
                              double height = ToolsUtils.calculateTextHeight(
                                  value: result, style: style);
                              height = height > 40 ? (height + 20) : 40;
                              double width = ToolsUtils.calculateTextWidth(
                                  value: result, style: style);
                              width = width > 300 ? 300 : width + 20;
                              return Container(
                                margin: const EdgeInsets.only(right: 5),
                                padding: const EdgeInsets.symmetric(
                                    vertical: 10, horizontal: 5),
                                width: width,
                                height: height,
                                alignment: Alignment.centerLeft,
                                decoration: BoxDecoration(
                                  color: HexColor(ColorsUtils.colorA9e9),
                                  borderRadius: BorderRadius.circular(3),
                                ),
                                child: Text(
                                  result,
                                  style: style,
                                ),
                              );
                            }),
                            Positioned(
                              width: 5,
                              height: 40,
                              top: 0,
                              right: 0,
                              child: CustomPaint(
                                size: const Size(5, 40),
                                painter: _SendCustomPainter(8),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  ClipRRect(
                    borderRadius: BorderRadius.circular(2),
                    child: Image.network(
                      'https://img2.baidu.com/it/u=4153415757,176581311&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
                      width: 40,
                      height: 40,
                      fit: BoxFit.fill,
                    ),
                  ),
                ],
              ).marginOnly(top: 10),
              ...controller.sends.map(
                (value) => Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Container(
                        padding: const EdgeInsets.only(right: 10),
                        alignment: Alignment.centerRight,
                        child: LimitedBox(
                          maxWidth: 300,
                          child: Stack(
                            clipBehavior: Clip.none,
                            children: [
                              LayoutBuilder(builder:
                                  (BuildContext ctx, BoxConstraints bx) {
                                // 计算高度 和宽度
                                final style = StylesUtils.customTextStyle(
                                  color: ColorsUtils.color0000,
                                  fontSize: StylesUtils.fontSize15,
                                );
                                double height = ToolsUtils.calculateTextHeight(
                                    value: value, style: style);
                                height = height > 40 ? (height + 20) : 40;
                                double width = ToolsUtils.calculateTextWidth(
                                    value: value, style: style);
                                width = width > 300 ? 300 : width;
                                return Container(
                                  margin: const EdgeInsets.only(right: 5),
                                  padding: const EdgeInsets.symmetric(
                                      vertical: 10, horizontal: 5),
                                  width: width,
                                  height: height,
                                  alignment: Alignment.centerLeft,
                                  decoration: BoxDecoration(
                                    color: HexColor(ColorsUtils.colorA9e9),
                                    borderRadius: BorderRadius.circular(3),
                                  ),
                                  child: Text(
                                    value,
                                    style: style,
                                  ),
                                );
                              }),
                              Positioned(
                                width: 5,
                                height: 40,
                                top: 0,
                                right: 0,
                                child: CustomPaint(
                                  size: const Size(5, 40),
                                  painter: _SendCustomPainter(8),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                    ClipRRect(
                      borderRadius: BorderRadius.circular(2),
                      child: Image.network(
                        'https://img2.baidu.com/it/u=4153415757,176581311&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
                        width: 40,
                        height: 40,
                        fit: BoxFit.fill,
                      ),
                    ),
                  ],
                ).marginOnly(top: 10),
              ),
            ],
          ),
        ),
        extendBody: true,
        bottomSheet: SafeArea(
          bottom: true,
          child: SizedBox(
            height: 50,
            child: Row(
              children: [
                Expanded(
                  child: Center(
                    child: TextField(
                      controller: controller.textEditingController,
                      cursorHeight: 20,
                      cursorWidth: 3,
                      cursorRadius: const Radius.circular(2),
                      cursorColor: HexColor(ColorsUtils.colorFf64),
                      style: StylesUtils.customTextStyle(
                        fontSize: StylesUtils.fontSize16,
                        color: ColorsUtils.color0000,
                      ),
                      textAlign: TextAlign.left,
                      textAlignVertical: TextAlignVertical.center,
                      textDirection: TextDirection.ltr,
                      keyboardType: TextInputType.text,
                      decoration: InputDecoration(
                        hintText: '请输入您要咨询的问题',
                        hintStyle: StylesUtils.customTextStyle(
                          fontSize: StylesUtils.fontSize16,
                          color: ColorsUtils.colorCccc,
                        ),
                        filled: true,
                        fillColor: Colors.white,
                        isDense: true,
                        isCollapsed: true,
                        contentPadding: const EdgeInsets.symmetric(
                            vertical: 10, horizontal: 20),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(2),
                          borderSide: BorderSide.none,
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(2),
                          borderSide: BorderSide.none,
                        ),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(2),
                          borderSide: BorderSide.none,
                        ),
                        constraints:
                            const BoxConstraints.expand(width: 275, height: 38),
                      ),
                      onChanged: (String keyword) {},
                      onSubmitted: (keyword) {
                        if (keyword.isEmpty) {
                          controller.sendMessage();
                        }
                      },
                    ),
                  ),
                ),
                Container(
                  height: 50,
                  padding: const EdgeInsets.only(right: 15),
                  alignment: Alignment.centerRight,
                  child: Wrap(
                    spacing: 15,
                    children: [
                      SvgUtils.assetName('u9177', width: 30, height: 30),
                      Icon(
                        CupertinoIcons.plus_circle,
                        size: 30,
                        color: HexColor(ColorsUtils.color0000),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class _SendCustomPainter extends CustomPainter {
  final double arrowHeight;

  _SendCustomPainter(this.arrowHeight);

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..style = PaintingStyle.fill
      ..strokeCap = StrokeCap.square
      ..color = HexColor(ColorsUtils.colorA9e9);
    Path path = Path();
    path.moveTo(0, (size.height - arrowHeight) / 2);
    path.lineTo(0, (size.height - arrowHeight) / 2 + arrowHeight);
    path.lineTo(size.width, (size.height - arrowHeight) / 2 + arrowHeight / 2);
    path.close();
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

class _ReceiveCustomPainter extends CustomPainter {
  final double arrowHeight;
  _ReceiveCustomPainter(this.arrowHeight);

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..style = PaintingStyle.fill
      ..strokeCap = StrokeCap.square
      ..color = Colors.white;
    Path path = Path();
    path.moveTo(size.width, (size.height - arrowHeight) / 2);
    path.lineTo(size.width, (size.height - arrowHeight) / 2 + arrowHeight);
    path.lineTo(0, (size.height - arrowHeight) / 2 + arrowHeight / 2);
    path.close();
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
